#include "include/swei_findbike.h"
#include "include/swei_cmd.h"
#include "global.h"
#define LOG_TAG TAG_TBOX
#include "include/port/swei_log.h"
#include "service/include/swei_downlink.h"
#include "comm/co_heartbeat.h"
#include "misc/misc_sound.h"

/**
 * @brief 寻车结束标志
 */
static uint8_t findbike_start = false;

/**
 * @brief 音频播报事件结束标志
 */
static void findbike_sound_playfinish_cb(TimerHandle_t pxTimer)
{
    /*此处为寻车十秒定时器到的事件处理*/
    log_i("findbike_cmd_finish_callback");
    if (findbike_start == false) {
        return;
    }

    if (NULL == pxTimer)
    {
        log_e("sound_timeout_callback pxTimer handle is none!\r\n");
        return;
    }

    findbike_start = false;
    /*清除寻车事件标志位*/
    // tbox_power_set_business_flag(SERVER_CMD_FIND_BIKE, 0);
}


/**
 * @brief 启动寻车回调
 * @param  cmd_id           My Param doc
 * @param  cmd_opcode       My Param doc
 * @param  p_data           My Param doc
 * @param  data_len         My Param doc
 * @return DLCMD_RET_TYPE_ENUM
 */
static DLCMD_RET_TYPE_ENUM findbike_event_callback(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char *p_data, uint32_t data_len)
{
    /*收到4G的寻车指令*/
    log_i("findbike_event_callback");
    if (findbike_start) {
        log_i("findbike already running!");
        return DLCMD_RET_FINISH;
    }

    co_aud_cmd(AUD_TYPE_FIND_BIKE);
    findbike_start = true;
    /**
     * @brief 触发寻车播报，采用超时接口，超时后调用回调
     */
    tbox_sound_play_with_timeout(SOUND_ID_FINDBIKE, 10000, findbike_sound_playfinish_cb);

    return DLCMD_RET_FINISH;
}
  

/**
 * @brief 停止寻车回调
 * @param  cmd_id           My Param doc
 * @param  cmd_opcode       My Param doc
 * @param  p_data           My Param doc
 * @param  data_len         My Param doc
 * @return DLCMD_RET_TYPE_ENUM
 */
static DLCMD_RET_TYPE_ENUM close_findbike_event_callback(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char *p_data, uint32_t data_len)
{
    log_i("close_findbike_event_callback");
    // swei_sound_alarm_stop();
    // if (findbike_start == false) {
    //     findbike_start = true;
    // }

    swei_netProtocol_ack_downlink_cmd(cmd_id, CMD_SUCCESS, true);

    return DLCMD_RET_FINISH;
}

/**
 * @brief 寻车功能初始化
 */
void swei_findbike_init(void)
{
    swei_downlink_cmd_register(DOWN_LINK_CMD_FIND_BIKE, findbike_event_callback);
    swei_downlink_cmd_register(DOWN_LINK_CMD_CLOSE_FIND_BIKE, close_findbike_event_callback);
}

/**
 * @brief Get the findbike status object
 * @return int32_t
 */
int32_t swei_findbike_status_get(void)
{
    return findbike_start;
}

/**
 * @brief 停止寻车功能
 * @return int32_t
 */
int32_t swei_findbike_stop(void)
{
    return 0;
}

// /**
//  * @brief 寻车事件处理
//  */
// void swei_findbike_process(void)
// {
//     if(!findbike_start) /* findbike_start 后续更改为rtos事件类型 */
//     {
//         /** 此处为寻车结束事件处理 */
//         findbike_start = true;

//         /**
//          * @brief 发送寻车响铃
//          */

//         log_i("findbike_process");
//     }
// }
